import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { createHtmlPlugin } from 'vite-plugin-html'
import compressPlugin from 'vite-plugin-compression'
import { visualizer } from 'rollup-plugin-visualizer'
import path from 'path'
import autoprefixer from 'autoprefixer';
import postcssPxtorem from 'postcss-pxtorem';
import viteImagemin from 'vite-plugin-imagemin';

export default defineConfig(({ mode }) => {
  // 环境判断
  const isProduction = mode === 'production'

  return {
    // 基础路径配置
    base: './',

    // 解析配置
    resolve: {
      alias: [
        { 
          find: '@', 
          replacement: path.resolve(__dirname, 'src') 
        },
        {
          find: '@i',
          replacement: path.resolve(__dirname, 'src/assets')
        }
      ],
      // 自动扩展名（比webpack更严格）
      extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue']
    },

    // 构建配置
    build: {
      // 生产环境禁用sourcemap
      sourcemap: false,
      cssMinify: true, // 开启 CSS 压缩

      // 更智能的代码分割（相比webpack chunks更高效）
      rollupOptions: {
        output: {
          manualChunks: (id) => {
            if (id.includes('node_modules')) {
              if (id.includes('element-plus')) return 'element'
              if (id.includes('vue')) return 'vue-vendor'
              return 'vendor'
            }
          },
          // 静态资源分类
          chunkFileNames: 'static/js/[name]-[hash].js',
          entryFileNames: 'static/js/[name]-[hash].js',
          assetFileNames: 'static/[ext]/[name]-[hash].[ext]'
        }
      },

      // 优化选项
      minify: 'terser',
      terserOptions: {
        compress: {
          drop_console: isProduction,
          drop_debugger: isProduction
        }
      },

      // 启用brotli压缩（需要服务器支持）
      brotliSize: true
    },

    // CSS配置（支持postcss和预处理器）
    css: {
      postcss: {
        plugins: [
          autoprefixer,
          postcssPxtorem({
            rootValue: 16,
            propList: ['*'],
            selectorBlackList: ['html'],
            mediaQuery: false
          })
        ]
      },
      // 拆分CSS文件（替代extract选项）
      modules: {
        generateScopedName: '[name]__[local]___[hash:base64:5]'
      }
    },

    // 插件配置
    plugins: [
      vue(),
      // HTML压缩
      createHtmlPlugin({
        minify: isProduction,
        inject: {
          data: {
            title: 'My App',
            injectScript: '<script src="/inject.js"></script>'
          }
        }
      }),
      // 压缩插件
      compressPlugin({
        verbose: true,
        disable: !isProduction,
        filter: /\.(js|css|html|svg)$/i,
        algorithm: 'gzip',
        threshold: 10240,
        compressionOptions: { level: 9 }
      }),
      compressPlugin({
        ext: '.br',
        algorithm: 'brotliCompress',
        threshold: 10240
      }),
      // 包分析
      visualizer({
        open: true,
        gzipSize: true,
        brotliSize: true
      }),
      viteImagemin({
        gifsicle: {
          optimizationLevel: 7,
          interlaced: false,
        },
        optipng: {
          optimizationLevel: 7,
        },
        mozjpeg: {
          quality: 80,
        },
        pngquant: {
          quality: [0.8, 0.9],
          speed: 4,
        },
        svgo: {
          plugins: [
            {
              name: 'removeViewBox',
              active: false,
            },
            {
              name: 'removeEmptyAttrs',
              active: false,
            },
          ],
        },
      }),
    ],

    // 开发服务器配置
    server: {
      port: 8080,
      proxy: {
        '/api': {
          target: 'http://localhost:8888',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, '')
        }
      }
    },

    // 优化配置
    optimizeDeps: {
      include: ['vue', 'vue-router', 'element-plus'],
      exclude: ['vue-demi']
    }
  }
})